package com.pactera.widget;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;

public class ImageLoaderWithCache {

	private static HashMap<String, SoftReference<Bitmap>> mImageCache;

	static {
		mImageCache = new HashMap<String, SoftReference<Bitmap>>();
	}

	public static Bitmap loadBitmapImage(DownloadInfo dLoadInfo) {
		String path=dLoadInfo.getLocalpath();
		if (mImageCache.containsKey(path)) {
			SoftReference<Bitmap> softReference = mImageCache.get(path);
			Bitmap bitmap = softReference.get();
			if (null != bitmap)
				return bitmap;
		}
		Bitmap bitmap=null;
		if(dLoadInfo.getWide()==0||dLoadInfo.getHeight()==0){
			bitmap = BitmapFactory.decodeFile(path);
		}else{
			try {
				bitmap=revitionImageSize(path,dLoadInfo.getWide(),dLoadInfo.getHeight());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(dLoadInfo.isIsCricle()){
			bitmap=GetRoundedCornerBitmap(bitmap);
		}
		if(dLoadInfo.isShadow()){
			bitmap=drawImageDropShadow(bitmap);
		}
		
		mImageCache.put(path, new SoftReference<Bitmap>(bitmap));
		return bitmap;
	}
	
	private static Bitmap drawImageDropShadow(Bitmap originalBitmap) {
		if(originalBitmap==null){
			return null;
		}
		// 模糊处理
		BlurMaskFilter blurFilter = new BlurMaskFilter(1,
				BlurMaskFilter.Blur.NORMAL);
		Paint shadowPaint = new Paint();
		// 设置透明度
		shadowPaint.setAlpha(50);
		shadowPaint.setColor(0x9d9d9d);
		/**
		 * 阴影制作涉及到一个重要	函数：
		 * 
		 * public void setShadowLayer (float radius, float dx, float dy, int
		 * color) radius：阴影半径 dx：X轴方向的偏移量 dy：Y轴方向的偏移量 color：阴影颜色
		 */
		shadowPaint.setShadowLayer(5f, 2.0f, 2.0f, 0x9d9d9d);
		shadowPaint.setMaskFilter(blurFilter);

		int[] offsetXY = new int[2];
		Bitmap shadowBitmap = originalBitmap
				.extractAlpha(shadowPaint, offsetXY);
		Bitmap shadowImage32 = null;
		SoftReference<Bitmap> softReference = null;
		Bitmap returnBitmap = null;
		try {
			shadowImage32 = shadowBitmap.copy(Bitmap.Config.ARGB_8888, true);
			Canvas c = new Canvas(shadowImage32);
			RectF dst=new RectF(offsetXY[0]+2, offsetXY[1]+2, originalBitmap.getWidth()-1, originalBitmap.getHeight()-1);
			c.drawBitmap(originalBitmap, null, dst, null);
//			c.drawBitmap(originalBitmap, offsetXY[0], offsetXY[1], null);
			softReference = new SoftReference<Bitmap>(shadowImage32);
			returnBitmap = softReference.get();
			if (returnBitmap != null) {
				return returnBitmap;
			} else {
				return originalBitmap;
			}
		} catch (Throwable e) {
			return originalBitmap;
		}
	}

	public static BitmapDrawable loadDrawableImage(DownloadInfo dLoadInfo) {
		return new BitmapDrawable(loadBitmapImage(dLoadInfo));
	}

	public static void releaseImage(String path) {
		if (mImageCache.containsKey(path)) {
			SoftReference<Bitmap> reference = mImageCache.get(path);
			Bitmap bitmap = reference.get();
			if (null != bitmap) {
				bitmap.recycle();
				bitmap = null;
			}
			mImageCache.remove(path);
		}
	}
	
	//生成圆角图片
	 public static Bitmap GetRoundedCornerBitmap(Bitmap bitmap) {
	  try {
	   Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
	     bitmap.getHeight(), Config.ARGB_8888);
	   Canvas canvas = new Canvas(output);     
	   final Paint paint = new Paint();
	   final Rect rect = new Rect(0, 0, bitmap.getWidth(),
	     bitmap.getHeight());  
	   final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(),
	     bitmap.getHeight()));
	   final float roundPx = 8;//设置这 可以改变取舍多少幅度
	   paint.setAntiAlias(true);
	   canvas.drawARGB(0, 0, 0, 0);
	   paint.setColor(Color.BLACK);  
	   canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
	   paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));    
	 
	   final Rect src = new Rect(0, 0, bitmap.getWidth(),
	     bitmap.getHeight());
	   
	   canvas.drawBitmap(bitmap, src, rect, paint); 
	   return output;
	  } catch (Exception e) {   
	   return bitmap;
	  }
	 }
	
	
	private static Bitmap revitionImageSize(String path, int wide,int height) throws IOException {
		// 取得图片
		InputStream temp = new FileInputStream(path);
		BitmapFactory.Options options = new BitmapFactory.Options();
		// 这个参数代表，不为bitmap分配内存空间，只记录一些该图片的信息（例如图片大小），说白了就是为了内存优化
		options.inJustDecodeBounds = true;
		// 通过创建图片的方式，取得options的内容（这里就是利用了java的地址传递来赋值）
		BitmapFactory.decodeStream(temp, null, options);
		// 关闭流
		temp.close();

		// 生成压缩的图片
		int i = 0;
		Bitmap bitmap = null;
		while (true) {
			// 这一步是根据要设置的大小，使宽和高都能满足
			if ((options.outWidth >> i <= wide)
					&& (options.outHeight >> i <= height)) {
				// 重新取得流，注意：这里一定要再次加载，不能二次使用之前的流！
				temp = new FileInputStream(path);
				// 这个参数表示 新生成的图片为原始图片的几分之一。
				options.inSampleSize = (int) Math.pow(2.0D, i);
				// 这里之前设置为了true，所以要改为false，否则就创建不出图片
				options.inJustDecodeBounds = false;

				bitmap = BitmapFactory.decodeStream(temp, null, options);
				break;
			}
			i += 1;
		}
		return bitmap;
	}

}
